package com.ky.manage.activity.aftersales;

import android.content.Intent;
import android.util.Log;
import android.view.Gravity;
import android.view.View;
import android.widget.ImageView;
import android.widget.TextView;

import com.ky.manage.BaseApplication;
import com.ky.manage.R;
import com.ky.manage.activityLifecycle.ActivityManagerUtil;
import com.ky.manage.adapter.AddressAdapter;
import com.ky.manage.base.BaseActivity;
import com.ky.manage.model.LoginUserInfo;
import com.ky.manage.model.response.AddressResp;
import com.ky.manage.ui.RecycleViewDivider;
import com.ky.manage.ui.dialog.CommonDialog;
import com.ky.manage.utils.ScreenUtils;
import com.ky.manage.utils.ToastUtils;
import com.ky.manage.utils.ZyUtils;
import com.ky.manage.utils.http.AsyncHttpUtils;
import com.ky.manage.utils.http.BusinessHttpReqUtils;
import com.loopj.android.http.TextHttpResponseHandler;
import com.scwang.smart.refresh.footer.ClassicsFooter;
import com.scwang.smart.refresh.header.ClassicsHeader;
import com.scwang.smart.refresh.layout.api.RefreshLayout;

import org.json.JSONException;
import org.json.JSONObject;

import java.lang.ref.WeakReference;
import java.util.ArrayList;

import androidx.fragment.app.FragmentActivity;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;
import cz.msebera.android.httpclient.Header;

import static com.ky.manage.utils.http.BusinessHttpReqUtils.SERVICE_DOMAIN;

/**
 *  管理收货地址
 */
public class ManagerAddressActivity extends BaseActivity implements AddressAdapter.DeleteListner {

    private AddressAdapter mAdapter;
    private int mCurListCnt;
    private RefreshLayout refreshLayout;
    private ImageView mToTopIv;
    private RecyclerView recyclerView;
    private boolean mIsReqListData = false;
    private TextView tvAddNewAddress;

    @Override
    protected int getLayoutId() {
        return R.layout.activity_address;
    }

    @Override
    protected void initView() {
        findTextView(R.id.page_title_tv, "地址管理");
        findView(R.id.back_iv, v -> {
            finish();
        });
        mToTopIv = findView(R.id.to_top_iv, v -> {
            //置顶
            recyclerView.smoothScrollToPosition(0);
            mToTopIv.setVisibility(View.GONE);
        });
        recyclerView = findView(R.id.recyclerView);
        LinearLayoutManager linearLayoutManager = new LinearLayoutManager(this);
        linearLayoutManager.setOrientation(LinearLayoutManager.VERTICAL);
        recyclerView.setLayoutManager(linearLayoutManager);
        recyclerView.addItemDecoration(new RecycleViewDivider(this, LinearLayoutManager.VERTICAL,
                ScreenUtils.dp2px(10), this.getColor(R.color.gray_light)));
        mAdapter = new AddressAdapter(this, R.layout.item_address, new ArrayList<>(), this);
        mAdapter.setOnItemClickListener((adapter , view , position) -> {
            //条目点击
            AddressResp.RowsDTO resp = mAdapter.getItem(position);
            Intent result = new Intent();
            result.putExtra("address", resp.getAddress());

            setResult(101, result);
            this.finish();
        });

        findView(R.id.tv_add_new_address, v -> {
            //置顶
            Intent intent = new Intent(this, AddressDetailActivity.class);
            intent.putExtra("tyep", 0);
            startActivity(new Intent(this, AddressDetailActivity.class));
        });

        recyclerView.setAdapter(mAdapter);
        mAdapter.notifyDataSetChanged();

        refreshLayout = findView(R.id.refreshLayout);
        refreshLayout.setRefreshHeader(new ClassicsHeader(this));
        refreshLayout.setRefreshFooter(new ClassicsFooter(this));
        refreshLayout.autoRefresh();
        refreshLayout.setOnRefreshListener(refreshlayout -> {
            if (mIsReqListData) {
                return;
            }

            requestAddressListData();
        });
        refreshLayout.setOnLoadMoreListener(refreshlayout -> {
            if (mIsReqListData) {
                return;
            }
            //mToTopIv.setVisibility(mCurPageIndex > 2 ? View.VISIBLE : View.GONE);
            requestAddressListData();
        });
    }

    /**
     * 无数据界面
     */
    private void showEmptyView() {
        mAdapter.getData().clear();
        mAdapter.setEmptyView(R.layout.layout_empty_data);
        mAdapter.notifyDataSetChanged();
    }

    @Override
    protected void onResume() {
        super.onResume();
    }

    @Override
    protected void onRestart() {
        super.onRestart();
        refreshLayout.autoRefresh();
    }

    @Override
    protected void initData() {
        requestAddressListData();
    }

    private void requestAddressListData() {
        LoginUserInfo loginUserInfo = BaseApplication.getLoginUserInfo();
        if (null == loginUserInfo || !ZyUtils.getInstance().isNetConnected()) {
            refreshLayout.finishRefresh();
            refreshLayout.finishLoadMore();
            return;
        }
        mIsReqListData = true;

        AsyncHttpUtils.getInstance().get(SERVICE_DOMAIN + "/appApi/getAddressList", new TextHttpResponseHandler() {
            @Override
            public void onFailure(int statusCode, Header[] headers, String responseString, Throwable throwable) {
                ZyUtils.getInstance().insertLog("requestAddressListData", "onFailure statusCode = " +
                        statusCode + ", errorResponse = "+ responseString + ", throwable = " + throwable.getMessage());
                ToastUtils.showRoundRectToast("获取收货地址失败：" + throwable.getMessage());
                Log.d("lhm", "requestAddressListData responseString = " + responseString);
                refreshLayout.finishRefresh();
                mIsReqListData = false;
            }

            @Override
            public void onSuccess(int statusCode, Header[] headers, String responseString) {
                Log.d("lhm", "requestAddressListData responseString = " + responseString);

                AddressResp resp = BusinessHttpReqUtils.getInstance().parseJsonObj(responseString, AddressResp.class);
                if(resp != null) {
                    if (resp.getCode() == 200) {
                        if(resp.getRows().size() <= 0) {
                            refreshLayout.finishRefreshWithNoMoreData();
                            showEmptyView();
                        } else {
                            mAdapter.setList(resp.getRows());
                            refreshLayout.finishRefreshWithNoMoreData();
                            refreshLayout.finishRefresh();
                        }
                    } else if(resp.getCode() == 401) {
                        //登陆失效，需重新登陆
                        BusinessHttpReqUtils.getInstance().autoPwdLogin(mCurActivity);
                    } else {
                        ToastUtils.showRoundRectToast("获取收货地址失败: " + resp.getMsg());
                    }
                } else {
                    ToastUtils.showRoundRectToast("获取收货地址失败");
                }
                mIsReqListData = false;
            }
        });
    }

    @Override
    public void OnAddressDelete(int key) {
        showConfirmDialog(key);
    }

    private CommonDialog mConfirmDialog;

    private void showConfirmDialog(int key) {
        if (ActivityManagerUtil.getInstance().isActivityDestroy(this)) {
            return;
        }
        if (null == mConfirmDialog) {
            WeakReference<FragmentActivity> activityWeakReference = new WeakReference<>(this);
            mConfirmDialog = CommonDialog.create(activityWeakReference.get().getSupportFragmentManager())
                    .setLayoutRes(R.layout.dialog_confirm)
                    .setViewListener(((v, baseDialog) -> {
                        if (null == activityWeakReference || null == activityWeakReference.get()
                                || activityWeakReference.get().isFinishing()) {
                            return;
                        }
                        //取消按钮
                        TextView cancelTv = v.findViewById(R.id.cancel_tv);
                        cancelTv.setOnClickListener(v1 -> {
                            hideEditDialog();
                        });
                        //确认按钮
                        TextView okTv = v.findViewById(R.id.ok_tv);
                        okTv.setOnClickListener(v1 -> {
                            //确定删除
                            requestDeleteAddress(key);
                        });

                    }))
                    .setDialogAnimationRes(R.style.Center_Zoom_Dialog)
                    .setGravity(Gravity.CENTER)
                    .setOnDismissListener(dialog -> {
                        //对话框关闭
                        hideEditDialog();
                    })
                    .setDialogWidth(ScreenUtils.dp2px(300))
                    .setDimAmount(0.2f)
                    .setCancelOutside(false)
                    .setKeyBackDismiss(false)
                    .setTag("ConfirmDialog");
        }

        if (mConfirmDialog.isShowing()) {
            return;
        }
        mConfirmDialog.show();
    }

    private void hideEditDialog() {
        if (null != mConfirmDialog) {
            mConfirmDialog.dismissAllowingStateLoss();
            mConfirmDialog = null;
        }
    }

    private void requestDeleteAddress(int key) {
        LoginUserInfo loginUserInfo = BaseApplication.getLoginUserInfo();
        if (null == loginUserInfo || !ZyUtils.getInstance().isNetConnected()) {
            refreshLayout.finishRefresh();
            refreshLayout.finishLoadMore();
            return;
        }
        mIsReqListData = true;

        AsyncHttpUtils.getInstance().delete(SERVICE_DOMAIN + "/appApi/addressDelete/" + key, new TextHttpResponseHandler() {
            @Override
            public void onFailure(int statusCode, Header[] headers, String responseString, Throwable throwable) {
                ZyUtils.getInstance().insertLog("requestDeleteAddress", "onFailure statusCode = " +
                        statusCode + ", errorResponse = "+ responseString + ", throwable = " + throwable.getMessage());
                ToastUtils.showRoundRectToast("删除收货地址失败：" + throwable.getMessage());
                Log.d("lhm", "requestDeleteAddress responseString = " + responseString);
                refreshLayout.finishRefresh();
                mIsReqListData = false;
            }

            @Override
            public void onSuccess(int statusCode, Header[] headers, String responseString) {
                Log.d("lhm", "requestDeleteAddress responseString = " + responseString);
                try {
                    JSONObject jsonObject = new JSONObject(responseString);
                    if(jsonObject != null) {
                        if(jsonObject.has("code")) {
                            if(jsonObject.getInt("code") == 200){
                                refreshLayout.autoRefresh();
                                hideEditDialog();
                            } else {
                                runOnUiThread(new Runnable() {
                                    @Override
                                    public void run() {
                                        try {
                                            ToastUtils.showToast("删除收货地址失败，错误信息：" + jsonObject.getString("msg"));
                                        } catch (JSONException e) {
                                            e.printStackTrace();
                                        }
                                    }
                                });
                            }
                        }
                    }
                } catch (JSONException e) {
                    e.printStackTrace();
                }

                mIsReqListData = false;
            }
        });
    }
}
